package com.spdd.mt.common.base.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spdd.mt.common.base.BaseEntity;
import com.spdd.mt.common.base.BaseService;
import com.spdd.mt.common.util.ConvertUtils;

import java.nio.charset.Charset;
import java.util.Collection;
import java.util.List;
import java.util.Map;


public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T> implements BaseService<T> {

    /**
     * 主键ID
     */
    private static final String ID = "id";

    protected void resetModelClass(Object entityObject) {
        log.debug("[" + entityObject.getClass().getName() + "]Bean不启动默认填充模式");
    }

    protected <D> D convertTarget(T entity, Class<D> clazz) {
        return ConvertUtils.sourceToTarget(entity, clazz);
    }

    protected <D> List<D> convertTarget(List<T> pageList, Class<D> clazz) {
        // Class<D> classz = (Class<D>) ReflectionKit.getSuperClassGenericType(getClass(), Mapper.class, 2);

        return ConvertUtils.sourceToTarget(pageList, clazz);
    }

    protected <D> Page<D> convertTarget(Page<T> pageList, Class<D> clazz) {
        // Class<D> classz = (Class<D>) ReflectionKit.getSuperClassGenericType(getClass(), Mapper.class, 2);

        Page<D> pageVoList = new Page<>();
        pageVoList.setCurrent(pageList.getCurrent());
        pageVoList.setSize(pageList.getSize());
        pageVoList.setTotal(pageList.getTotal());
        pageVoList.setRecords(ConvertUtils.sourceToTarget(pageList.getRecords(), clazz));

        return pageVoList;
    }

    /**
     * 获取分页对象，默认按添加时间倒序排列
     *
     * @param params 分页查询参数
     */
    public Page<T> getPage(Map<String, Object> params) {
        return this.getPage(params, "create_time", false);
    }

    public boolean saveOrUpdateBatch(Collection<T> entityList) {
        return this.saveOrUpdateBatch(entityList, 1000);
    }

    /**
     * 获取分页对象
     *
     * @param params            分页查询参数
     * @param defaultOrderField 默认排序字段
     * @param isAsc             排序方式
     */
    @Override
    public Page<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {

        // 分页参数
        long curPage = 1;
        long limit = 10;

        if (params.get("page") != null) {
            curPage = NumberUtil.parseLong(String.valueOf(params.get("page")));
        }
        if (params.get("size") != null) {
            limit = NumberUtil.parseLong(String.valueOf(params.get("size")));
        }

        // 分页对象
        Page<T> page = new Page<>(curPage, limit);

        // 分页参数
        params.put("page", page);

        // 排序
        String orderField = (String) params.get("orderField");
        String order = (String) params.get("order");
        if (StrUtil.isNotBlank(orderField) && StrUtil.isNotBlank(order)) {
            if ("ASC".equalsIgnoreCase(order)) {
                return page.addOrder(OrderItem.asc(orderField));
            } else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        // 多级排序
        List<Map> orderFields = JSONUtil.toList(JSONUtil.parseArray(URLUtil.decode((String) params.get("orderFields"), Charset.defaultCharset())), Map.class);

        if (CollectionUtil.isNotEmpty(orderFields)) {
            orderFields.forEach(m -> {
                String field = (String) m.keySet().iterator().next();
                String value = (String) m.values().iterator().next();
                page.addOrder(("ascending".equalsIgnoreCase(value) || "asc".equalsIgnoreCase(value)) ?
                        OrderItem.asc(StrUtil.toUnderlineCase(field)) :
                        OrderItem.desc(StrUtil.toUnderlineCase(field))
                );
            });
        }

        // 没有排序字段，则不排序
        if (StringUtils.isBlank(defaultOrderField)) {
            return page;
        }

        // 默认排序
        if (isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        } else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }

        return page;
    }
}
